//
//  YSPageCollectionViewLayout.m
//  YSEmoticonKeyboard
//
//  Created by MOLBASE on 2017/12/22.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSPageCollectionViewLayout.h"

@interface YSPageCollectionViewLayout ()
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *cellAttrMarray;
@property (nonatomic, assign) CGFloat maxWidth;
@end

@implementation YSPageCollectionViewLayout

- (instancetype)init {
    if (self = [super init]) {
        self.rowCount = 2;
        self.columnCount = 4;
        self.maxWidth = 0;
        self.cellAttrMarray = @[].mutableCopy;
    }
    return self;
}

- (void)prepareLayout {
    [super prepareLayout];
    
    // 0.计算item宽度和高度
    CGFloat itemW = (self.collectionView.bounds.size.width - self.sectionInset.left - self.sectionInset.right - self.minimumInteritemSpacing * (self.columnCount - 1)) / self.columnCount;
    CGFloat itemH = (self.collectionView.bounds.size.height - self.sectionInset.top - self.sectionInset.bottom - self.minimumLineSpacing * (self.rowCount - 1)) / self.rowCount;
    
    // 1.获取一共多少组
    NSInteger sectionCount = [self.collectionView numberOfSections];
    
    // 2.获取每组中有多少个Item
    NSInteger pageCount = 0;
    for (NSInteger i = 0; i < sectionCount; i++) {
        NSInteger itemCount = [self.collectionView numberOfItemsInSection:i];
        
        for (NSInteger j = 0; j < itemCount; j++) {
            // 2.1.获取Cell对应的IndexPath
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            
            // 2.2.根据indexPath创建UICollectionViewLayoutAttributes
            UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            
            // 2.3.设置attr的frame
            // 2.3.1.计算j所在页
            NSInteger page = j / (self.rowCount * self.columnCount);
            // 2.3.2.计算j所在页第几个
            NSInteger index = j % (self.rowCount * self.columnCount);
            
            CGFloat itemY = self.sectionInset.top + (itemH + self.minimumLineSpacing) * (index / self.columnCount);
            CGFloat itemX = (pageCount + page) * self.collectionView.bounds.size.width + self.sectionInset.left + (itemW + self.minimumInteritemSpacing) * (index % self.columnCount);
            attr.frame = CGRectMake(itemX, itemY, itemW, itemH);
            
            // 2.4.保存attr
            [self.cellAttrMarray addObject:attr];
        }
        
        pageCount += (itemCount - 1) / (self.columnCount * self.rowCount) + 1;
        
        // 3.计算最大值
        self.maxWidth = pageCount * self.collectionView.bounds.size.width;
    }
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.cellAttrMarray;
}

- (CGSize)collectionViewContentSize {
    return CGSizeMake(self.maxWidth, 0);
}

@end
